var express = require('express');
var router = express.Router();
var config = require('../config');
var path = require('path');
var fs = require('fs');
var gm = require('gm');
var utils = require('../utils');

/* GET home page. */
router.get('/', function(req, res, next) {
  console.log('render app');
  res.sendFile(path.join(config.webpackBuildPath, 'index.html'));
});

router.get('/static/image/:img', async function(req, res, next) {
    var img = req.params.img;
    var originalImage = utils.getOriginalName(img), targetImage;
    var isThumb = !!req.query.thumb, width = parseInt(req.query.size);
    width = isNaN(width) ? -1 : width;

    try {
        if (isThumb) {
            targetImage = await utils.makeThumbIfNotExisted(originalImage);
        } else if (width > 0) {
            targetImage = await utils.compressAndGetPath(originalImage, width);
        } else {
            var isExisted = await utils.isFileExists(originalImage);
            if (isExisted) {
                targetImage = originalImage;
            } else {
                targetImage = utils.getErrorName();
            }
        }
    } catch(e) {
        targetImage = utils.getErrorName();
    }
    res.sendFile(targetImage);
});

module.exports = router;
